﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.Office.Server;
using System.Text;
using Microsoft.SharePoint.Utilities;
using Square.Activity;


namespace Square.CONTROLTEMPLATES.Square
{
    public partial class deleteColleagues : UserControl
    {
        SquareActivityHelper sHelper;

        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        public void lbtn_Delete_Colleagues_Click(object sender, EventArgs e)
        {
            string[] rId = hd_dRequestID.Value.Split(',');

            #region ## Properties
            string _siteUrl = SPContext.Current.Site.Url;
            string _webUrl = SPContext.Current.Web.Url;
            string _listUrl = "/my/Lists/Sq_Colleagues";
            //string _listName = "Sq_Colleagues";

       
            UserProfile _pageUserProfile;
            #endregion

            string _accountName = string.Empty;

            if (Request.QueryString["accountname"] != null)
                _accountName = Request.QueryString["accountname"];
            else
                _accountName = this.Page.User.Identity.Name;

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite _site = new SPSite(_siteUrl))
                    {
                        using (SPWeb _web = _site.OpenWeb())
                        {
                            SPList _list = _web.GetList(_listUrl);
                            //SPList _list = _web.Lists[_listName];
                            
                            SPServiceContext context = SPServiceContext.GetContext(_site);
                            //ServerContext context = ServerContext.GetContext(_site);
                            UserProfileManager upm = new UserProfileManager(context);
                            foreach (string sId in rId)
                            {
                                StringBuilder sb = new StringBuilder();
                                sb.Append("<Where>");
                                sb.Append("     <Eq>");
                                sb.Append("         <FieldRef Name=\"Title\" />");
                                sb.AppendFormat("   <Value Type=\"Text\">{0}</Value>", sId);
                                sb.Append("     </Eq>");
                                sb.Append("</Where>");

                                SPQuery sq = new SPQuery();
                                sq.Query = sb.ToString();

                                SPListItemCollection _items = _list.GetItems(sq);

                                foreach (SPListItem _item in _items)
                                {
                                    _pageUserProfile = upm.GetUserProfile(_accountName);
                                    UserProfile _colleaguesProfile = upm.GetUserProfile(long.Parse(_item["ColleagueRecordId"].ToString()));
                                    DeleteColleague(_siteUrl, _accountName, _colleaguesProfile.DisplayName);

                                    string[] _colleagueName = _colleaguesProfile.DisplayName.Split('\\');

                                    bool bSave = false;
                                    SquareActivities aType = new SquareActivities();
                                    aType = SquareActivities.SquarePeopleAccept;

                                    sHelper = new SquareActivityHelper();
                                    //<img src=\"" + userInfo["PictureURL"].Value + "\" class=\"list_people_img\" />"
                                    //bSave = sHelper.SaveActivity(this.Page, aType, rName  + "님의 요청을 수락하습니다.");
                                    bSave = sHelper.SaveActivity(this.Page, aType, " had to cancel a request for " + "<a href=\"" + _colleaguesProfile.PersonalUrl + "\" target=\"_blank\">" + _colleagueName[1] + "</a>");
                                    
                                    _web.AllowUnsafeUpdates = true;
                                    _item.Delete();
                                    _list.Update();
                                    _web.AllowUnsafeUpdates = false;
                                }
                            }
                        }
                    }
                });
            }
            catch {  }

            //Page.ClientScript.RegisterStartupScript(this.GetType(), null, "fn_refreshG();", true);
        }

        /// <summary>
        /// Deletes a colleague relationship.
        /// </summary>
        /// <param name="requestUrl">URL of the SharePoint site to connect to.</param>
        /// <param name="loginName">Login name of a user having access to 
        /// the SharePoint site (for example, DOMAIN\User).</param>
        /// <param name="colleagueLoginName">Login name of the user to add 
        /// to loginName's colleagues (for example, DOMAIN\User).</param>
        public static void DeleteColleague(string requestUrl, string loginName, string colleagueLoginName)
        {
            using (SPSite siteCollection = new SPSite(requestUrl))
            {
                using (SPWeb webSite = siteCollection.OpenWeb())
                {
                    // Retrieve the ServerContext of the site collection.SPServiceContext
                    SPServiceContext serverContext = SPServiceContext.GetContext(siteCollection);
                    //ServerContext serverContext = ServerContext.GetContext(siteCollection);

                    // Connect to the UserProfileManager of the SharePoint Web application.
                    UserProfileManager userProfileManager = new UserProfileManager(serverContext);

                    // Check whether the user profile and the colleague user profile exist, and that they are not
                    // the same user.
                    if (userProfileManager.UserExists(loginName) &&
                        userProfileManager.UserExists(colleagueLoginName) &&
                        string.Compare(loginName, colleagueLoginName, true) != 0)
                    {
                        // Retrieve user profiles.
                        UserProfile userProfile = userProfileManager.GetUserProfile(loginName);
                        UserProfile userProfileColleague = userProfileManager.GetUserProfile(colleagueLoginName);

                        // Check whether colleagueLoginName is already a colleague.
                        if (userProfile.Colleagues.IsColleague(userProfileColleague.ID) == true)
                        {
                            userProfile.Colleagues[userProfileColleague].Delete();

                            // Save the modification made to the user profile.
                            userProfile.Commit();
                        }
                    }
                }
            }
        }

        //spgroup의 멤버들을 삭제
        private void ClearMemberInGroup(string strSPGroupName, SPWeb _cWeb)
        {
            Guid oSiteID = SPContext.Current.Site.ID;
            Guid oWebID = SPContext.Current.Web.ID;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                if (Is_SPGroup_Exist(strSPGroupName, _cWeb))
                {
                    using (SPSite _site = new SPSite(oSiteID))
                    {
                        using (SPWeb _web = _site.OpenWeb(oWebID))
                        {
                            SPGroup SP_WGGroup = _web.SiteGroups[strSPGroupName];

                            foreach (SPUser removeuser in SP_WGGroup.Users)
                            {
                                SP_WGGroup.RemoveUser(removeuser);
                            }
                        }
                    }
                }
            });
        }

        //spgroup에 해당 멤버가 있는지 확인
        private bool Is_SPGroup_Exist(string GroupName, SPWeb _web)
        {
            SPGroupCollection siteGroups = _web.SiteGroups;
            foreach (SPGroup group in siteGroups)
            {
                if (group.Name == GroupName)
                {
                    return true;
                }
            }
            return false;
        }
    }
}
    

